package zoz.cool.jahub.service;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import zoz.cool.jahub.domain.JahubLoginLog;
import zoz.cool.jahub.utils.RequestUtil;

import java.time.LocalDateTime;

@Slf4j
@Service
public class UserService {

    @Resource
    private JahubLoginLogService jahubLoginLogService;

    @Async
    public void insertLoginLog(Long userId) {
        JahubLoginLog jahubLoginLog = new JahubLoginLog();
        jahubLoginLog.setUserId(userId);
        jahubLoginLog.setCreateTime(LocalDateTime.now());
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        Assert.notNull(attributes, "无法获取请求信息！");
        HttpServletRequest request = attributes.getRequest();
        jahubLoginLog.setIp(RequestUtil.getRequestIp(request));
        jahubLoginLogService.save(jahubLoginLog);
        log.info("记录用户登录日志：{}", jahubLoginLog);
    }
}
